namespace Hellophp;

class Config {

	private static _dir = null;
	private static _config = [];

	private static function _init() {
		
		if (null !== self::_dir) {
			return;
		}
		let self::_dir = defined("CONFIG_DIR") ? CONFIG_DIR : (defined("APP_PATH") ? APP_APTH : ".")."/config";
		if (is_file(self::_dir."/global.php")) {
			self::loadConfig(require(self::_dir."/global.php"));
		}
	}

    public static function loadConfig(data, prefix = "") {

        if (!data || !is_array(data)) {
            return;
        }
        var key, value;
        for (key, value in data) {
            let key = prefix . key;
            if (!array_key_exists(key, self::_config)) {
                let self::_config[key] = value;
            }
            if (is_array(value)) {
                self::loadConfig(value, key . ".");
            }
        }
    }

	public static function get(key, defaultValue = null) {

		self::_init();
        if (array_key_exists(key, self::_config)) {
            return self::_config[key];
        }

        // 尝试自动加载配置文件
        var parts;
        let parts = explode(".", key);
        var path = "", prefix = "";
        let path .= self::_dir;
        var i;
        var data;
        for (i in range(0, count(parts) - 1)) {
            let prefix .= (i == 0 ? parts[i] : "." . parts[i]);
            let path .= "/" . parts[i];
			if (is_file(path . ".php")) {
				let data = require(path . ".php");
				if (is_array(data)) {
					let self::_config[prefix] = data;
					self::loadConfig(data, prefix . ".");
				}
			}
        }

        // 若还是没有取到，返回默认值
        if (array_key_exists(key, self::_config)) {
            return self::_config[key];
        }
        return defaultValue;
    }
}
